package com.csap.framework.integration.consumer;

import com.aliyun.openservices.ons.api.MessageListener;
import com.csap.framework.integration.MessageFilterType;
import com.csap.mybatisplus.core.toolkit.CollectionUtils;
import com.csap.mybatisplus.core.toolkit.StringPool;
import lombok.Builder;
import lombok.Data;
import lombok.ToString;
import org.apache.commons.lang3.RandomUtils;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * @author yangchengfu
 * @description 阿里云消息队列自动化配置
 * @dataTime 2020年-09月-22日 15:28:00
 **/
@Data
public class EnableRocketmqBean {
    /**
     * 消息队列消费者存储
     */
    private Map<String, RocketmqBean> rocketmqBeans = new ConcurrentHashMap<>(16);

    /**
     * 添加Class
     *
     * @param rocketmqBea
     */
    public EnableRocketmqBean add(RocketmqBean rocketmqBea) {
        if (!rocketmqBeans.containsKey(rocketmqBea.getAClass())) {
            rocketmqBeans.put(rocketmqBea.getAClass().getName(), rocketmqBea);
        }
        return this;
    }

    /**
     * 过滤
     *
     * @param v    过滤的具体值
     * @param type 1 topic 2 tag 3 key
     * @return
     */
    public RocketmqBean filter(String v, MessageFilterType type) {
        List<String> tags = rocketmqBeans.keySet().stream().filter(i -> {
            RocketmqBean rocketmqBean = rocketmqBeans.get(i);
            if (type.equals(MessageFilterType.TOPIC)) {
                return rocketmqBean.getTopic().equals(StringPool.ASTERISK) || rocketmqBean.getTopic().equals(v);
            } else if (type.equals(MessageFilterType.TAG)) {
                return rocketmqBean.getTag().equals(StringPool.ASTERISK) || rocketmqBean.getTag().equals(v);
            } else {
                return rocketmqBean.getKey().equals(StringPool.ASTERISK) || rocketmqBean.getKey().equals(v);
            }
        }).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(tags)) {
            return rocketmqBeans.get(tags.get(RandomUtils.nextInt(0, tags.size())));
        }
        return null;
    }

    /**
     * 获取目标对象
     *
     * @param name 消费对象
     * @return 返回具体消费对象
     */
    public RocketmqBean get(String name) {
        return rocketmqBeans.get(name);
    }


    @Data
    @Builder
    @ToString
    public static class RocketmqBean {

        /**
         * 目标class
         */
        private Class<? extends MessageListener> aClass;

        /**
         * 订阅主题
         *
         * @return
         */
        private String topic;

        /**
         * 标签
         *
         * @return
         */
        private String tag;

        /**
         * 表达式
         *
         * @return
         */
        private String expression;

        /**
         * 消息《即业务代码》
         *
         * @return
         */
        private String key;
    }
}
